package com.zja.servlet;


import com.zja.dao.ArticleDao;
import com.zja.dao.Impl.ArticleDaoImpl;
import com.zja.model.Article;
import com.zja.model.JsonResponse;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author JA
 * @date: 2025/5/6
 * description:公开文章展示（分页）
 */
@WebServlet("/api/home/articles")
public class HomeArticleServlet extends HttpServlet {
    private final ArticleDao articleDao = new ArticleDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");

        // 获取分页参数，默认为第1页，每页10条
        int page = 1;
        int pageSize = 10;
        try {
            page = Integer.parseInt(req.getParameter("page"));
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        } catch (Exception ignored) {}

        int offset = (page - 1) * pageSize;

        // 查询数据
        List<Article> articles = articleDao.selectPublicArticles(offset, pageSize);
        int total = articleDao.countPublicArticles();

        // 构造响应数据
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("articles", articles);

        // 返回 JSON
        ServletUtil.writeJsonResponse(resp, JsonResponse.success("获取成功", data));
    }
}
